package exhibition.app.nexd.cn.presenter;

import android.content.Context;
import android.util.Log;

import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.litesuits.orm.db.model.ConflictAlgorithm;
import com.squareup.okhttp.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import exhibition.app.nexd.cn.application.NexdApplication;
import exhibition.app.nexd.cn.model.OrderForm;
import exhibition.app.nexd.cn.ui.ivew.IMainActivityView;
import exhibition.app.nexd.cn.utils.APIUtils;
import exhibition.app.nexd.cn.utils.OkHttpClientManager;

/**
 * Main presenter
 * <p/>
 * Created by wangxu on 16/4/21.
 */
public class MainPresenter extends BasePresenter<IMainActivityView> {

    private Map<Integer, OrderForm> orderFormMap;
    private LiteOrm dbExhibition;

    public MainPresenter(Context context, IMainActivityView iView) {
        super(context, iView);
        dbExhibition = NexdApplication.getInstance().getLiteOrm();
        orderFormMap = NexdApplication.getInstance().getOrderFormMap();
        getOrdersFromDB(NexdApplication.getInstance().getUserId());
    }

    private void getOrdersFromDB(int userId) {
        orderFormMap.clear();
        Log.i("userId", userId + "");
        if (userId != 0) {
            List<OrderForm> orderForms = dbExhibition.query(new QueryBuilder<>(OrderForm.class).where("userId=?", new String[]{userId + ""}));
            Log.d(this.getClass().getSimpleName(), Arrays.toString(orderForms.toArray()));
            for (int i = 0; i < orderForms.size(); i++) {
                OrderForm orderForm = orderForms.get(i);
                orderFormMap.put(orderForm.getHireId(), orderForm);
            }
//            if (orderForms.size() != 0) {
//                NexdApplication.IS_HAVE_ORDER = true;
//            }
        }
    }

    public void reCalculation() {
        double totalPrice = 0;
        int totalCount = 0;
        for (Map.Entry<Integer, OrderForm> entry : orderFormMap.entrySet()) {
            OrderForm orderForm = entry.getValue();
            totalPrice += orderForm.getNum() * orderForm.getPrice() + orderForm.getHireDeposit();
            totalCount += orderForm.getNum();
        }
        iView.updateGoods(totalCount, totalPrice);
    }

    public void payOrder() {
//        if (NexdApplication.IS_HAVE_ORDER) {
//            iView.showToast("当前已有订单存在,不允许修改");
//            return;
//        }
        if (orderFormMap.size() != 0) {
            //提交订单
            StringBuilder insertHireUrl = new StringBuilder();
            JSONArray data = new JSONArray();
            for (Map.Entry<Integer, OrderForm> entry : orderFormMap.entrySet()) {
                OrderForm orderForm = entry.getValue();
                ArrayList<OrderForm> isExistOrderForm = dbExhibition.query(new QueryBuilder<OrderForm>(OrderForm.class).where("orderFormId", new String[]{orderForm.getOrderFormId()}));
                if (isExistOrderForm.size() > 0) {
                    dbExhibition.update(orderForm, ConflictAlgorithm.Replace);
                } else {
                    dbExhibition.save(orderForm);
                }
                JSONObject hire = new JSONObject();
                try {
                    hire.put("exhibitUserId", NexdApplication.getInstance().getUserId());
                    hire.put("hireName", orderForm.getTitle());
                    hire.put("hireDays", orderForm.getDays());
                    hire.put("hireNums", orderForm.getNum());
                    hire.put("hireDeposit", 2.00);
                    double totalPrice = orderForm.getNum() * orderForm.getPrice() + orderForm.getHireDeposit();
                    hire.put("hireTotal", totalPrice);
                    data.put(hire);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            insertHireUrl.append(APIUtils.INSERT_HIRE);
            Map<String, String> param = new HashMap<>();
            param.put("appKey", "f4b5aeaa1776f7af714e0663fa2e50b2");
            param.put("data", data.toString());
            Log.i("insertHireUrl", insertHireUrl.toString() + param.toString());
            OkHttpClientManager.postAsyn(insertHireUrl.toString(), param, new OkHttpClientManager.ResultCallback<String>() {

                @Override
                public void onError(Request request, Exception e) {
                    iView.showToast("网络异常");
                    e.printStackTrace();
                }

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject object = new JSONObject(response);
                        if (object.getBoolean("isSuccess")) {
                            iView.onPayOrderSuccess();
                            dbExhibition.save(NexdApplication.getInstance().getHires());
                        } else {
                            iView.showToast(object.getString("msg"));
                        }
                    } catch (JSONException e) {
                        iView.showToast("数据解析异常");
                        e.printStackTrace();
                    }
                }
            });
        } else {
            iView.showToast("您没有添加新的订单~");
            iView.onPayOrderSuccess();
        }
    }
}
